/*
 * Copyright (C) 2019 ByteDance Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bytedance.scene.utlity;

import ohos.aafwk.ability.Ability;
import ohos.biometrics.authentication.BiometricAuthentication;

public class CancellationSignal {
    private boolean mIsCanceled;
    private OnCancelListener mOnCancelListener;
    private Object mCancellationSignalObj;

    public CancellationSignal() {
    }

    public boolean isCanceled() {
        synchronized (this) {
            return mIsCanceled;
        }
    }

    public void throwIfCanceled() {
        if (isCanceled()) {
            throw new RuntimeException();
        }
    }

    public void cancel() {
        final OnCancelListener listener;
        final Object obj;
        synchronized (this) {
            if (mIsCanceled) {
                return;
            }
            mIsCanceled = true;
            listener = mOnCancelListener;
            obj = mCancellationSignalObj;
        }

        if (listener != null) {
            listener.onCancel();
        }
        if (obj != null) {
            ((BiometricAuthentication) obj).cancelAuthenticationAction();
        }
    }

    public void setOnCancelListener(OnCancelListener listener) {
        synchronized (this) {
            if (mOnCancelListener == listener) {
                return;
            }
            mOnCancelListener = listener;
            if (!mIsCanceled || listener == null) {
                return;
            }
        }
        listener.onCancel();
    }

    public Object getCancellationSignalObject(Ability ability) {
        synchronized (this) {
            if (mCancellationSignalObj == null) {
                try {
                    mCancellationSignalObj = BiometricAuthentication.getInstance(ability);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                if (mIsCanceled) {
                    ((BiometricAuthentication) mCancellationSignalObj).cancelAuthenticationAction();
                }
            }
            return mCancellationSignalObj;
        }
    }

    private void waitForCancelFinishedLocked() {

    }

    /**
     * Listens for cancellation.
     */
    public interface OnCancelListener {
        /**
         * Called when {@link CancellationSignal#cancel} is invoked.
         */
        void onCancel();
    }
}
